<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";

import { getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import { setToken } from "@/utils/auth";
import { addPathMatch } from "@/router/utils";
import {
  usePermissionStoreHook,
  filterRoutes
} from "@/store/modules/permission";
// import { v4 as uuidv4 } from "uuid";
import apiService from "@/services/apiService";
import { useRoleStore } from "@/store/modules/useRoleStore";
import { storeToRefs } from "pinia";
import adminRoutes from "@/router/modules/admin";

import { Tickets } from "@element-plus/icons-vue";

import { ElMessage } from "element-plus";

defineOptions({
  name: "Login"
});
const roleStore = useRoleStore();
const { role, name } = storeToRefs(roleStore);

const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

const ruleForm = reactive({
  // username: "mianyang",
  // password: "mianyang001"
  username: "",
  password: "",
  verifycode: ""
});

const captchaImage = ref("");

const codeText = ref("");

const getCode = () => {
  // let code = ''
  // var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
  var arr = "01234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPSADFGHJKLZXCVBNM";
  var str = "";
  for (var i = 0; i < 4; i++) {
    var num = Math.floor(Math.random() * (arr.length - 1) + 0);
    str += arr[num];
  }
  let checkCode = str;

  codeText.value = checkCode;

  // 创建一个 canvas 元素
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");

  // 设置 canvas 的尺寸为 100x40
  canvas.width = 100;
  canvas.height = 40;

  // 绘制背景色
  ctx.fillStyle = "#f0f0f0";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 设置字体
  ctx.font = "20px Arial";
  ctx.fillStyle = "black";

  // 获取文本的宽度
  const textWidth = ctx.measureText(checkCode).width;

  // 计算水平居中的起始位置
  const x = (canvas.width - textWidth) / 2;

  // 设置垂直居中的起始位置
  const y = (canvas.height + 20) / 2;

  // 绘制验证码字符（居中显示）
  ctx.fillText(checkCode, x, y);

  // 如果你想加入一些干扰线
  for (let i = 0; i < 5; i++) {
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.strokeStyle = "rgba(0, 0, 0, 0.2)";
    ctx.stroke();
  }

  // 将 canvas 转为图片并显示
  captchaImage.value = canvas.toDataURL("image/png");
};

const AccountInformation = reactive({
  username: "mianyang",
  password: "mianyang001",
  verifycode: ""
});
// 动态加载路由的函数
// function addDynamicRoutes() {
//   console.log(adminRoutes);
//   if (roleStore.role == "0") {
//     console.log("11111");

//     // 判断用户是否登录（根据你的实际情况调整）
//     adminRoutes.forEach(route => {
//       router.addRoute(route); // 动态添加路由
//     });
//   }
// }
const onLogin = async (formEl: FormInstance | undefined) => {
  // loading.value = true;
  if (!formEl) return;

  if (ruleForm.username != AccountInformation.username) {
    ElMessage({
      message: "输入的账号错误",
      type: "warning"
    });
    return;
  }

  if (ruleForm.password != AccountInformation.password) {
    ElMessage({
      message: "输入的密码错误",
      type: "warning"
    });
    return;
  }

  if (ruleForm.verifycode == "") {
    ElMessage({
      message: "请输入验证码",
      type: "warning"
    });
    return;
  }

  if (ruleForm.verifycode.toUpperCase() != codeText.value.toUpperCase()) {
    ElMessage({
      message: "输入的验证码错误",
      type: "warning"
    });
    return;
  }

  await formEl.validate((valid, fields) => {
    if (valid) {
      const parmas = {
        msgid: "AdminLogin",
        token: "BC65FD34-931E-6E6D-7970-EFD67A547B56",
        seq: "99AA5D15-2352-C61B-F5A9-328417C77A25",
        body: {
          account: ruleForm.username,
          password: ruleForm.password
        }
      };

      apiService
        .post("", parmas)
        .then((res: any) => {
          // console.log(res);

          if (res.data.code == 200) {
            localStorage.setItem("userid", res.data.body.id);
            localStorage.setItem("role", res.data.body.role);
            roleStore.setRole(res.data.body.role);
            roleStore.setName(res.data.body.name);
            roleStore.setUserid(res.data.body.id);
            if (res.data.body.role == "0") {
              setToken({
                username: res.data.body.name,
                roles: ["0"],
                accessToken: res.data.body.token
              } as any);
            } else {
              setToken({
                username: res.data.body.name,
                roles: ["1"],
                accessToken: res.data.body.token
              } as any);
            }
            // console.log(res);

            // 全部采取静态路由模式
            usePermissionStoreHook().handleWholeMenus([]);
            addPathMatch();
            // console.log(router.options.routes);
            // filterRoutes(router.options.routes[0].children)
            if (res.data.body.role == "0") {
              router.push("/fenxi/index");
            } else {
              router.push("/yuyue/index");
            }

            loading.value = false;
            // addDynamicRoutes();

            message("登录成功", { type: "success" });
            // 刷新当前路由

            // const text = getToken();
            // console.log("测试token", text);
          } else {
            loading.value = false;
            message("登录失败", { type: "error" });
            // console.log("接口异常", err);
          }
        })
        .catch(err => {});

      // setToken({
      //   username: "admin",
      //   roles: ["admin"],
      //   accessToken: "eyJhbGciOiJIUzUxMiJ9.admin"
      // } as any);
      // // 全部采取静态路由模式
      // usePermissionStoreHook().handleWholeMenus([]);
      // addPathMatch();
      // router.push("/");
      // message("登录成功", { type: "success" });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  getCode();
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>

          <el-form ref="ruleFormRef" :model="ruleForm" size="large">
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入账号',
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  placeholder="账号"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>
            <Motion :delay="150">
              <div style="display: flex; gap: 20px">
                <el-form-item prop="verifycode">
                  <el-input
                    v-model="ruleForm.verifycode"
                    clearable
                    placeholder="验证码"
                    :prefix-icon="Tickets"
                  />
                </el-form-item>
                <div @click="getCode">
                  <img
                    class="img4"
                    :src="captchaImage"
                    alt="验证码"
                    style="width: 100px; height: 40px"
                  />
                </div>
              </div>
            </Motion>
            <Motion :delay="250">
              <el-button
                class="w-full mt-4"
                size="default"
                type="primary"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                登录
              </el-button>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
